package control.render;

import java.awt.Color;

import data.complex.Ray;
import data.hierarchy.World;
import data.render.IRenderMethod;

public class UnbiasedRenderWorker implements Runnable{
  private World world;
  private MonteCarloImage mcImage;
  private IRenderMethod renderMethod;
  private boolean stopped = false;
  private boolean disableFocus;
  
  public UnbiasedRenderWorker(World world, MonteCarloImage mcImage, IRenderMethod renderMethod, boolean disableFocus){
    this.world = world;
    this.mcImage = mcImage;
    this.renderMethod = renderMethod;
    this.disableFocus = disableFocus;
  }
  
  @Override
  public void run() {
    double u, v, imgX, imgY, sideRatio;
    sideRatio = (double)mcImage.getHeight() / mcImage.getWidth();
    
    while(!stopped){
      u = Math.random();
      v = Math.random();
      
      imgX = u * (mcImage.getWidth() - 1);
      imgY = v * (mcImage.getHeight() - 1);
      
      Ray ray;
      if(disableFocus)
        ray = world.getCamera().getRay(u * 2 - 1, (v * 2 - 1) * sideRatio);
      else
        ray = world.getCamera().getMonteCarloRay(u * 2 - 1, (v * 2 - 1) * sideRatio);
      Color imgCol = renderMethod.getPixel(ray);
      
      mcImage.addQuadSample(imgX, imgY, imgCol);
    }
  }

  public void stop(){
    stopped = true;
  }
}
